package com.ccx.demo.business.common.controller;

import com.ccx.demo.business.common.entity.TabErrorLog;
import com.ccx.demo.business.common.service.ErrorLogService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.support.annotations.VueSwaggerGroup;
import com.support.mvc.encrypt.AesApiId;
import com.support.mvc.entity.IUser;
import com.support.mvc.entity.base.Page;
import com.support.mvc.entity.base.Result;
import com.utils.enums.Code;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 对外接口：异常日志记录
 *
 * @author 谢长春 on 2022-02-16 V20220301
 */
@Api(tags = "异常日志记录")
//@ApiSort() // 控制接口排序
@RequestMapping("/error-log")
@Controller
@Slf4j
@RequiredArgsConstructor
public class ErrorLogController {

    private final ErrorLogService service;
    @VueSwaggerGroup
    @GetMapping("/page/{number}/{limit}")
    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_load')")
    @ApiOperation(value = "1.分页查询异常日志记录", tags = {""})
    @ApiOperationSupport(
            order = 1,
            author = "谢长春",
            includeParameters = {"number", "limit", "orderBy", "traceId", "createUserId", "updateUserId", "deleted"}
    )
    @ResponseBody
    public Result<TabErrorLog> page(
            @ApiIgnore @AuthenticationPrincipal final IUser user,
            @ApiParam(required = true, value = "页码", example = "1") @PathVariable final int number,
            @ApiParam(required = true, value = "每页条数，最大值1000", example = "10") @PathVariable final int limit,
            final TabErrorLog condition) {
        return new Result<TabErrorLog>().execute(result -> { // Controller 方法逻辑写在这里
            result.setSuccess(service.page(condition, Page.of(number, limit)));
        });
    }

//// 非必要情况下不要开放列表查询方法，因为没有分页控制，容易内存溢出。大批量查询数据应该使用分页查询
//    @GetMapping
//    // @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_load')")
//    @ApiOperation(value = "2.列表查询异常日志记录", tags = {""})
//    @ApiOperationSupport(
//            order = 2,
//            author = "谢长春",
//            includeParameters = {"orderBy", "traceId", "createUserId", "updateUserId", "deleted"}
//    )
//    @ResponseBody
//    public Result<TabErrorLog> list(@ApiIgnore @AuthenticationPrincipal final IUser user, final TabErrorLog condition) {
//        return new Result<TabErrorLog>().execute(result -> { // Controller 方法逻辑写在这里
//            result.setSuccess(service.list( condition ));
//        });
//    }
//
@VueSwaggerGroup
    @GetMapping("/{encryptId}")
    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_load')")
    @ApiOperation(value = "3.按 id 查询异常日志记录", tags = {""})
    @ApiOperationSupport(order = 3, author = "谢长春")
    @ResponseBody
    public Result<TabErrorLog> findById(
            @ApiIgnore @AuthenticationPrincipal final IUser user,
            @ApiParam(required = true, value = "加密id", example = "encryptId") @PathVariable final String encryptId
    ) {
        return new Result<TabErrorLog>().execute(result -> { // Controller 方法逻辑写在这里
            final AesApiId.AesId decrypt = AesApiId.decrypt(encryptId);
            result.setSuccess(service.findById(decrypt.getLongId()).orElse(null));
        });
    }

//    @PostMapping
//    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_insert')")
//    @ApiOperation(value = "4.新增异常日志记录", tags = {""})
//    @ApiOperationSupport(
//            order = 4,
//            author = "谢长春",
//            includeParameters = {
//                    "body.traceId", "body.message"
//            })
//    @ResponseBody
//    public Result<TabErrorLog> insert(
//            @ApiIgnore @AuthenticationPrincipal final IUser user,
//            @RequestBody final TabErrorLogInsertDTO body
//    ) {
//        return new Result<TabErrorLog>().execute(result -> { // Controller 方法逻辑写在这里
//            result.setSuccess(service.insert(body, user.getId()));
//        });
//    }
//
//    @PutMapping("/{encryptId}")
//    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_update')")
//    @ApiOperation(value = "5.修改异常日志记录", tags = {""})
//    @ApiOperationSupport(
//            order = 5,
//            author = "谢长春",
//            ignoreParameters = {
//                    "body.traceId", "body.message"
//            })
//    @ResponseBody
//    public Result<Void> update(
//            @ApiIgnore @AuthenticationPrincipal final IUser user,
//            @ApiParam(required = true, value = "加密id", example = "encryptId") @PathVariable final String encryptId,
//            @RequestBody final TabErrorLogUpdateDTO body
//    ) {
//        return new Result<Void>().call(() -> { // Controller 方法逻辑写在这里
//            final AesApiId.AesId decrypt = AesApiId.decrypt(encryptId);
//            body.setUpdateTime(decrypt.getUpdateTime());
//            service.update(decrypt.getLongId(), user.getId(), body);
//        });
//    }
@VueSwaggerGroup
    @PatchMapping("/{encryptId}")
    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_delete')")
    @ApiOperation(value = "6.逻辑删除异常日志记录", tags = {""})
    @ApiOperationSupport(order = 6, author = "谢长春")
    @ResponseBody
    public Result<Void> markDeleteById(
            @ApiIgnore @AuthenticationPrincipal final IUser user,
            @ApiParam(required = true, value = "加密id", example = "encryptId") @PathVariable final String encryptId
    ) {
        return new Result<Void>().call(() -> {
            final AesApiId.AesId decrypt = AesApiId.decrypt(encryptId);
            service.markDeleteById(decrypt.getLongId(), user.getId());
        });
    }
    @VueSwaggerGroup
    @PatchMapping
    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_delete')")
    @ApiOperation(value = "7.逻辑删除异常日志记录", tags = {""})
    @ApiOperationSupport(
            order = 7,
            author = "谢长春",
            params = @DynamicParameters(name = "EncryptIdArray", properties = {
                    @DynamicParameter(name = "EncryptIdArray", value = "加密id", example = "[encryptId,encryptId]", required = true, dataTypeClass = String[].class)
            })
    )
    @ResponseBody
    public Result<Void> markDeleteByIds(
            @ApiIgnore @AuthenticationPrincipal final IUser user,
            @RequestBody final Set<String> body
    ) {
        return new Result<Void>().call(() -> {
            Code.A00002.assertNonEmpty(body, "请至少选择一条数据");
            final List<AesApiId.AesId> decryptList = body.stream().map(AesApiId::decrypt).collect(Collectors.toList());
            service.markDeleteByIds(
                    decryptList.stream().map(AesApiId.AesId::getLongId).collect(Collectors.toSet())
                    , decryptList.stream().map(AesApiId.AesId::getUpdateTime).collect(Collectors.toSet())
                    , user.getId()
            );
        });
    }

//    @PatchMapping("/{encryptId}")
//    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_delete')")
//    @ApiOperation(value = "8.物理删除异常日志记录", tags = {""})
//    @ApiOperationSupport(order = 8, author = "谢长春")
//    @ResponseBody
//    public Result<Void> deleteById(
//            @ApiIgnore @AuthenticationPrincipal final IUser user,
//            @ApiParam(required = true, value = "加密id", example = "encryptId") @PathVariable final String encryptId) {
//        return new Result<Void>().call(() -> {
//            final AesApiId.AesId decrypt = AesApiId.decrypt(encryptId);
//            service.deleteById(decrypt.getLongId(), user.getId());
//        });
//    }
//
//    @PatchMapping
//    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_delete')")
//    @ApiOperation(value = "9.物理删除异常日志记录", tags = {""})
//    @ApiOperationSupport(
//            order = 9,
//            author = "谢长春",
//            params = @DynamicParameters(name = "EncryptIdArray", properties = {
//                    @DynamicParameter(name = "EncryptIdArray", value = "加密id", example = "[encryptId,encryptId]", required = true, dataTypeClass = String[].class)
//            })
//    )
//    @ResponseBody
//    public Result<Void> deleteByIds(
//            @ApiIgnore @AuthenticationPrincipal final IUser user,
//            @RequestBody final Set<String> body
//    ) {
//        return new Result<Void>().call(() -> {
//            Code.A00002.assertNonEmpty(body, "请至少选择一条数据");
//            final List<AesApiId.AesId> decryptList = body.stream().map(AesApiId::decrypt).collect(Collectors.toList());
//            service.deleteByIds(
//                    decryptList.stream().map(AesApiId.AesId::getLongId).collect(Collectors.toSet())
//                    , decryptList.stream().map(AesApiId.AesId::getUpdateTime).collect(Collectors.toSet())
//                    , user.getId()
//            );
//        });
//    }
//
}
